package com.chinaisafe.user.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.chinaisafe.gateway.client.auth.UaaAuthHelper;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.schema.Column;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;

/**
 * CustomTenantHandler
 * Description：自定义租户字段Handler
 *
 * @author 上上谦
 * @date 2024/7/5 10:56
 */
@Component
public class CustomTenantHandler implements TenantLineHandler {

    @Value("${chinaisafe.tenant.ignoreTableName}")
    private List<String> ignoreTableNameList;

    @Override
    public Expression getTenantId() {
        String tenancyCode = UaaAuthHelper.getCurrentTenancyCode();
        // 从上下文获取当前租户id
        return new StringValue(tenancyCode);
    }

    @Override
    public String getTenantIdColumn() {
        return "tenancy_code";
    }

    @Override
    public boolean ignoreTable(String tableName) {
        if (CollectionUtil.isNotEmpty(ignoreTableNameList) && ignoreTableNameList.contains(tableName)) {
            return true;
        }
        return TenantLineHandler.super.ignoreTable(tableName);
    }

    @Override
    public boolean ignoreInsert(List<Column> columns, String tenantIdColumn) {
        return TenantLineHandler.super.ignoreInsert(columns, tenantIdColumn);
    }
}
